package org.project.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

public class AsyncLast extends AsyncTask<Void, Void, Object> {
	
	private HttpUriRequest request_;

	private AsyncLastCallback callback_;
	
	private HttpResponse response_;
	
	private Exception exception_;
	
	private String content_;

	public AsyncLast(HttpUriRequest request, AsyncLastCallback callback) {
		super();
		Log.d("AsyncLast", "Entered Constructor");
		request_ = request;
		callback_ = callback;
	}

	@Override
	protected Object doInBackground(Void... params) {
		try{
			HttpClient client = new DefaultHttpClient();
			response_ = client.execute(request_);
			
			String val = "Result of request to ["+request_.getURI()+"]\nStatus Code:"+response_.getStatusLine().getStatusCode()+"\n";
			val += response_.getStatusLine().getReasonPhrase();
			String line = null;
			StringBuilder sb = new StringBuilder();
			/**
			 * Step 4: Your code should convert the contents of the response_.getEntity().getContent()
			 * InputStream into a String and append it to val.
			 */
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(response_.getEntity().getContent()));
				  
				while ((line = reader.readLine()) != null) {
					   sb.append(line + "\n");
				}
			} catch (IOException e) {
				   e.printStackTrace();
			}
			String httpresponseval = sb.toString();
			val += httpresponseval;
			content_ = val;
			
		}catch(Exception e){
			exception_ = e;
		}
		return response_;
	}

	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		
		if(exception_ != null){
			callback_.onError4(exception_);
		}
		else {
			callback_.onResponse4(response_,content_);
		}
	}
	
}